import express from 'express';
// 引入文章相关控制器
import * as articles from '../../controllers/articles.js'
// 引入工具函数
import { cleanArticleContent } from '../../util/util.js'
const router = express.Router();

// 1.文章搜索接口
router.get("/search", async (req, res, next) => {
  try {
    console.log('开始处理 /search 请求...');
    const { key, type, page = 1, perpage = 6 } = req.query; 
    
    let data = await articles.searchArticles(key || '', type, parseInt(page), parseInt(perpage));
    let countResult = await articles.searchArticlesCount(key || '', type);
    let [{ count }] = countResult; // 关键字文章总数
    let pages = Math.ceil(count / parseInt(perpage));  // 呈现的总页数
    
    res.send({
      code: 200,
      msg: "查询成功",
      pages,
      page: parseInt(page),
      data: data.map(item => ({
        id: item.id,
        title: cleanArticleContent(item.title),
        intro: cleanArticleContent(item.intro || item.content || ""),
        cover: item.cover,
        category: item.categoryName || item.type, 
        read: item.read,
        comment: item.comments || 0, 
        date: item.date
      }))
    });
  } catch (error) {
    console.error('搜索接口错误:', error.message);
    res.status(500).send({
      code: 500,
      msg: "搜索失败: " + error.message
    });
  }
});

export default router;
